package com.hh.releasenode.bean;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtils
 * @Description redis工具类
 * @Author KunxianLi
 * Date 2020/6/30 11:35
 * Version 1.0
 **/
@Component
public class RedisBean {

    /**
     *默认过期时间
     **/
    public static final long DEFAULT_EXPIRE = 60*60*24; //24h

    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    public Object get(String key){

        return StringUtils.isNotBlank(key) ? redisTemplate.opsForValue().get(key): null;
    }

    /**
     * @Author KunxianLi
     * @Description 设置默认过期时间的值
     * @Date 2020/7/6 18:12
     * @Param [key, value]
     * @return void
     **/
    public void set(String key,Object value){

        redisTemplate.opsForValue().set(key,toJson(value),DEFAULT_EXPIRE);
    }

    /**
     * @Author KunxianLi
     * @Description 设置指定过期时间的值
     * @Date 2020/7/6 18:12
     * @Param [key, value]
     * @return void
     **/
    public void set(String key,Object value,long expire){

        redisTemplate.opsForValue().set(key,toJson(value));
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key,expire, TimeUnit.SECONDS);
        }
    }

    /**
     * @Author KunxianLi
     * @Description 删除指定的key
     * @Date 2020/7/6 18:12
     * @Param [key]
     * @return boolean
     **/
    public boolean del(String key){
         return redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    public String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return JSONObject.toJSONString(object);
    }

}
